package weaver.formmode.customjavacode.modeexpand.huangwm.SW003;

import com.alibaba.fastjson.JSONObject;
import com.api.customization.huangwm.dao.SW003.LoggingDao;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.DateTools;
import com.customization.huangwm.utils.HttpRequest;
import com.customization.huangwm.utils.LogTool;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew;
import weaver.formmode.interfaces.impl.huangwm.SW003.ImportWareHouseBeforeAction;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestInfo;
import weaver.system.SysRemindWorkflow;

import java.util.*;

/**
 * @Author Huangwm
 * @Date 2022-10-19
 * @Version 1.0
 * @Description TODO 倉庫庫存模塊手工新建的時候更新物料檔案庫存和期初庫存 用於保存/保存並新建動作
 **/
public class AddQuantityByWareHouse extends AbstractModeExpandJavaCodeNew {
    private LogTool logTool = new LogTool("/log/SW003/huangwm/model/action/AddQuantityByWareHouse", false);
    private DateTools dateTools = new DateTools();
    private DBTools dbTools = new DBTools();
    private LoggingDao loggingDao = new LoggingDao();

    @Override
    public Map<String, String> doModeExpand(Map<String, Object> param) {
        Map<String, String> result = new HashMap<String, String>();

        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);

            User user = (User) param.get("user");
            int billid = -1;//数据id
            int modeid = -1;//模块id
            String importtype = param.getOrDefault("importtype", "0").toString();
            RequestInfo requestInfo = (RequestInfo) param.get("RequestInfo");

            if (requestInfo != null) {
                try {
                    billid = Util.getIntValue(requestInfo.getRequestid());
                    modeid = Util.getIntValue(requestInfo.getWorkflowid());
                    if (billid > 0 && modeid > 0) {
                        BaseBean baseBean = new BaseBean();
                        String eop_reqUrl = baseBean.getPropValue("SW003", "eop_reqUrl");
                        if (eop_reqUrl.isEmpty()) {
                            result.put("errmsg", "獲取SW003.peoperties中的eop_reqUrl爲空");
                            result.put("flag", "false");
                            return result;
                        }
                        String eop_reqToken = baseBean.getPropValue("SW003", "eop_reqToken");
                        if (eop_reqToken.isEmpty()) {
                            result.put("errmsg", "獲取SW003.peoperties中的eop_reqToken爲空");
                            result.put("flag", "false");
                            return result;
                        }

                        Map<String, String> mainDatas = new HashMap<>();
                        String sql1 = "select * from uf_003_WarehouseNum where id=" + billid;
                        RecordSet rs1 = new RecordSet();
                        rs1.execute(sql1);
                        rs1.next();
                        String[] columns = rs1.getColumnName();
                        for (int i = 0; i < columns.length; i++) {
                            mainDatas.put(columns[i].toLowerCase(), rs1.getString(columns[i]));
                        }

                        String assetid = mainDatas.get("assetcode");//物料id
                        Double currentQuantity = Double.valueOf(mainDatas.get("num1"));
                        Double quantity = getAssetCounts(rs1,assetid);//获取物料当前总数
                        Double total = currentQuantity+quantity;
                        Map<String,String> assetInfo = dbTools.getAssetAllFieldoByID(rs1,assetid);

                        HttpRequest httpRequest = new HttpRequest();
                        String times = httpRequest.getTimestamp();
                        //寫入用友期初庫存
                        JSONObject params_Bill = new JSONObject();
                        params_Bill.put("reqNb", times);
                        params_Bill.put("reqLang", "zh");
                        params_Bill.put("reqToken", eop_reqToken);
                        Map<String, Object> reqData_Bill = new HashMap<>();
                        List<Map<String, Object>> bill = new ArrayList<>();//reqData中的bill
                        Map<String, Object> bill_data = new HashMap<>();
                        //billHead内容
                        Map<String, Object> billHead = new HashMap<>();
                        billHead.put("id",times);
                        billHead.put("cbilltypecode","4A");
                        billHead.put("dbilldate",dateTools.getCurrentDate());
                        billHead.put("pk_corp","MW");
                        billHead.put("vbillcode","");
                        billHead.put("cdispatcherid","21");
                        billHead.put("cdeptid",dbTools.getYyDepCode(user.getUID() + ""));
                        billHead.put("pk_calbody","MW");
                        String  cwarehouseid = dbTools.getWarehouse(assetInfo.get("managedep"));
                        billHead.put("cwarehouseid",cwarehouseid);
                        billHead.put("coperatorid",dbTools.getWorkCode(user.getUID()+""));
                        billHead.put("fbillflag","2");
                        billHead.put("vnote","期初-倉庫库存手动新增-"+cwarehouseid);
                        //添加billhead内容
                        bill_data.put("billHead",billHead);

                        List<Map<String, Object>> billBody = new ArrayList<>();
                        RecordSet rs2 = new RecordSet();
                        Map<String, Object> billBody_data = new HashMap<>();
                        billBody_data.put("cinventoryid",dbTools.getAssetCode(rs1,assetid));
                        billBody_data.put("dbizdate",dateTools.getCurrentDate());
                        billBody_data.put("ninnum",currentQuantity);
                        billBody_data.put("nprice","0");
                        billBody_data.put("nmny","0");
                        //添加body内容
                        billBody.add(billBody_data);

                        bill_data.put("billBody",billBody);
                        bill.add(bill_data);
                        reqData_Bill.put("bill",bill);
                        params_Bill.put("reqData",reqData_Bill);

                        //更新物料库存
                        boolean f = updateAssetCounts(rst,assetid,total);
                        if(!f){
                            result.put("errmsg", "更新物料["+assetid+"]庫存失敗 請聯係管理員刪除本條數據");
                            result.put("flag", "false");
                            return result;
                        }

                        logTool.writeLog("---期初入庫傳入用友參數如下---");
                        logTool.writeLog(JSONObject.toJSONString(params_Bill));
                        JSONObject json_Bill = httpRequest.CallApiPost(eop_reqUrl + "/eop/eapToUfida/icBillBegin", JSONObject.toJSONString(params_Bill));
                        logTool.writeLog("---期初入庫傳入用友結果如下---");
                        logTool.writeLog(JSONObject.toJSONString(json_Bill));
                        loggingDao.wrtieLog("0", "/eop/eapToUfida/icBillBegin", JSONObject.toJSONString(params_Bill), JSONObject.toJSONString(json_Bill));
                        if(json_Bill==null || !json_Bill.getString("state").equals("0")){
                            rst.rollback();
                            del(billid);
                            result.put("errmsg", "EAP倉庫庫存期初庫存對接失敗 請聯係管理員刪除本條數據");
                            result.put("flag", "false");
                            return result;
                        }
                        //記錄入庫日志
                        loggingDao.wrtieInventoryLog(rst,"1", assetInfo.get("assetcode"), currentQuantity, billid+"", "倉庫庫存新建", mainDatas.get("warehouse"),
                                "","4","",user.getUID()+"",assetInfo.get("assetname"));

                        rst.commit();//提交更新庫存
                    } else {
                        rst.rollback();
                        del(billid);
                        result.put("errmsg", "保存動作擴展接口执行失败 billid为空 請聯係管理員刪除本條數據");
                        result.put("flag", "false");
                        return result;
                    }
                } catch (Exception e) {
                    rst.rollback();
                    del(billid);
                    e.printStackTrace();
                    logTool.writeLog("保存動作擴展接口異常" + e.getMessage());
                    result.put("errmsg", "保存動作擴展接口異常,請聯係管理員刪除本條數據 msg=" + e.getMessage());
                    result.put("flag", "false");
                }
            }
        return result;
    }

    /**
     * 獲取物料当前的库存
     * @param rs
     * @param id
     * @return
     */
    private Double getAssetCounts(RecordSet rs,String id){
        if(id.isEmpty()) return 0.00;
        rs.execute("select totalQuantity from uf_003_AssteInfo where id="+id);
        rs.next();
        return rs.getDouble("totalQuantity");
    }

    /**
     * 导入仓库库存后更新物料档案中的库存信息
     * @param rs
     * @param id
     * @param total
     * @return
     */
    private boolean updateAssetCounts(RecordSetTrans rs, String id, Double total) throws Exception {
        String sql = "update uf_003_AssteInfo set totalQuantity="+total+",InventoryQuantity="+total+"-NVL(usedQuantity,0) where id="+id;
        boolean result =  rs.execute(sql);
        logTool.writeLog("導入倉庫庫存后更新檔案庫存["+sql+"] result="+result);
        return result;
    }

    private synchronized void del(int billid){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                RecordSet rs = new RecordSet();
                rs.execute("delete from uf_003_WarehouseNum where id="+billid);
            }
        },3000);
    }
}
